<template>
  <div class="chat-container">
    <!-- 左侧历史记录 -->
    <div class="history-sidebar custom-scrollbar">
      <div class="sidebar-header">
        <h2>历史记录</h2>
        <el-button
          type="primary"
          icon="Plus"
          circle
          @click="createNewSession"
        ></el-button>
      </div>
      <ul v-infinite-scroll="handleScroll">
        <li
          v-for="(session, index) in sessions"
          :key="index"
          @click="loadDialogue(session)"
          :class="{ active: session.id === activeSessionId }"
        >
          <div class="session-item">
            <span v-if="!session.isEditing">{{
              truncatedSessionName(session.session_name)
            }}</span>
            <input
              v-else
              :value="session.session_name"
              @input="updateSessionName(session, $event.target.value)"
              @click.stop
              class="truncated-input"
            />
            <div class="session-actions">
              <el-button
                v-if="!session.isEditing"
                type="text"
                @click.stop="toggleEditSession(session)"
                >编辑</el-button
              >
              <el-button
                v-if="session.isEditing"
                :icon="Select"
                type="plain"
                class="red-icon"
                style="color: green"
                @click.stop="saveSessionName(session)"
              ></el-button>
              <el-button
                type="text"
                style="color: red"
                @click.stop="deleteSession(session.id)"
                v-if="!session.isEditing"
                >删除</el-button
              >
              <el-button
                v-if="session.isEditing"
                :icon="CloseBold"
                type="plain"
                class="red-icon"
                style="color: red"
                @click.stop="toggleEditSession(session)"
              ></el-button>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-window">
      <div class="messages custom-scrollbar" ref="messagesContainer">
        <!-- 消息列表 -->
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.sender]"
        >
          <div class="message-content" v-if="message.sender == 'user'">
            {{ message.content }}
          </div>
          <div class="message-content" v-if="message.sender == 'bot'">
            <MdPreview
              style="background-color: #ecf0f1; border-radius: 10px"
              :modelValue="message.content"
              showCodeRowNumber
            ></MdPreview>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="isLoading" class="message bot">
          <div class="message-content">
            <!-- <div class="loading">加载中...</div> -->
            <el-button loading class="transparent-button">Loading</el-button>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="dropdown">
          <el-select
            size="large"
            :disabled="selectIsLoading"
            v-model="selectedModel"
            placeholder="请选择模型"
            :loading="selectIsLoading"
            @change="handleModelChange"
          >
            <el-option
              v-for="model in models"
              :key="model.id"
              :label="model.model_name_zh"
              :value="model.id"
            />
          </el-select>
        </div>
        <el-input
          style="margin-right: 5px; border-radius: 12px"
          :disabled="inputDisabled"
          size="large"
          v-model="query"
          placeholder="输入问题"
          @keyup.enter="sendQuery"
        >
          <template #append>
            <el-button
              :icon="More"
              circle
              style="background-color: transparent; color: black"
              @click="sessionConfig"
            />
          </template>
        </el-input>
        <el-button
          @click="sendQuery"
          :disabled="inputDisabled"
          size="large"
          style="margin-top: 9px"
          >发送</el-button
        >
      </div>
    </div>
  </div>

  <!-- 文件处理抽屉 -->
  <form-drawer
    ref="registerFormDrawerRef"
    title="额外配置"
    size="30%"
    confirmText="启动处理"
    destroyOnClose
    @submit="registerOnSubmit"
  >
    <el-form
      :model="registerForm"
      ref="registerFormRef"
      :rules="registerRules"
      label-width="100px"
      size="large"
      label-position="top"
    >
      <el-form-item prop="knowledge_ids" label="知识库配置" style="width: 40%">
        <el-select
          size="large"
          v-model="registerForm.knowledge_ids"
          filterable
          multiple
          clearable
          collapse-tags
          placeholder="绑定知识库"
          popper-class="custom-header"
          :max-collapse-tags="1"
          style="width: 300px;"
        >
          <template #header>
            <el-checkbox
              v-model="checkAll"
              :indeterminate="indeterminate"
              @change="handleCheckAll"
            >
              全部
            </el-checkbox>
          </template>
          <el-option
            v-for="item in cities"
            :key="item.id"
            :label="item.knowledge_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="network" label="是否开启联网搜索" style="width: 40%">
        <el-switch
          v-model="registerForm.network"
          inline-prompt
          size="large"
          style="width: 100%"
        >
          <template #active-action>
            <span class="custom-active-action">🌐</span>
          </template>
          <template #inactive-action>
            <span class="custom-inactive-action">🚫</span>
          </template>
        </el-switch>
      </el-form-item>
    </el-form>
  </form-drawer>
</template>

<script setup>
import FormDrawer from '~/components/FormDrawer.vue' // 解决会默认直接展示的问题
import {
  EditPen,
  Select,
  CloseBold,
  Search,
  Document,
  More
} from '@element-plus/icons-vue'
import { ElLoading } from 'element-plus'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { fa, pa } from 'element-plus/es/locale/index.mjs'
import { onMounted, ref, nextTick, watch } from 'vue'
import {
  ChatCreateSession,
  ChatSessionList,
  ChatDialogueList,
  ChatAnswer,
  ChatSaveSession,
  ChatDeleteSession,
  ChatModelList,
  AllKnowledge,
  SessionConfig
} from '~/api/manager'
import { sessionAddConfig } from '~/composables/chatManger'

const query = ref('') // 输入的问题
const sessions = ref([]) // 历史会话列表
const activeSessionId = ref(null)
const messages = ref([])
const isLoading = ref(false)
const messagesContainer = ref(null)
const inputDisabled = ref(false)
const models = ref([]) // 模型列表
const selectedModel = ref('') // 当前选中的模型
const selectIsLoading = ref(false)
// 历史会话的记录
const sessionListCount = ref(0)
const sessionPage = ref(1)
const sessionLimit = ref(12)
// 聊天历史的记录
const dialogueListCount = ref(0)
const dialoguePage = ref(1)
const indeterminate = ref(false)
const checkAll = ref(false)
const network = ref(null)

const {
  formDrawerRef: registerFormDrawerRef,
  formRef: registerFormRef,
  form: registerForm,
  onSubmit: registerOnSubmit,
  rules: registerRules,
  openRegisterForm
} = sessionAddConfig()

// 配置会话的额外属性
const sessionConfig = () => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  const session_id = activeSessionId.value
  registerForm.session_id = session_id
  SessionConfig(session_id).then((res) => {
    registerForm.knowledge_ids = res.data.knowledge_ids.map((item) => item.id)
    console.log(registerForm.knowledge_ids)
    registerForm.network = res.data.network
    }).finally(() => {
      loadingInstance.close()
      openRegisterForm()
    })
  
}

const cities = ref([])

watch(
  () => registerForm.knowledge_ids,
  (val) => {
    if (val.length === 0) {
      // 如果没有选中任何知识库
      checkAll.value = false
      indeterminate.value = false
    } else if (val.length === cities.value.length) {
      // 如果选中的知识库数量等于 cities 的长度
      checkAll.value = true
      indeterminate.value = false
    } else {
      // 部分选中
      indeterminate.value = true
    }
  }
)

const userAllKnowledge = () => {
  AllKnowledge().then((res) => {
    console.log(res)
    cities.value = res.data
  })
}

const handleCheckAll = (val) => {
  indeterminate.value = false
  if (val) {
    // 全选：将 cities 中的所有知识库 ID 赋值给 knowledge_ids
    registerForm.knowledge_ids = cities.value.map((item) => item.id)
  } else {
    // 取消全选：清空 knowledge_ids
    registerForm.knowledge_ids = []
  }
}

// 获取模型数据
const fetchModels = () => {
  selectIsLoading.value = true
  ChatModelList({})
    .then((res) => {
      models.value = res.data
    })
    .finally(() => {
      selectIsLoading.value = false // 无论成功或失败，都会关闭加载状态
    })
}

// 新建会话
const createNewSession = () => {
  ChatCreateSession({ session_name: '新建会话' }).then((res) => {
    loadSessions(sessionPage.value)
  })
}
// 编辑会话名称
// 限制名称的展示字数
const truncatedSessionName = (name) => {
  console.log(name)

  const maxLength = 4 // 最大显示字符数
  return name.length > maxLength ? name.slice(0, maxLength) + '...' : name
}

const updateSessionName = (session, newName) => {
  session.session_name = newName // 更新实际的值
}
// 修改状态位
const toggleEditSession = (session) => {
  session.isEditing = !session.isEditing
}
// 修改会话名称
const saveSessionName = (session) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  ChatSaveSession({
    session_id: session.id,
    session_name: session.session_name
  })
    .then((res) => {
      console.log(res)
      toggleEditSession(session)
    })
    .finally(() => {
      loadingInstance.close()
    })
}
// 修改会话模型
const handleModelChange = (selectedId) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  ChatSaveSession({
    session_id: activeSessionId.value,
    model_id: selectedId
  })
    .then((res) => {
      console.log(res)
    })
    .finally(() => {
      loadingInstance.close()
    })
}
// 删除会话
const deleteSession = (sessionId) => {
  ChatDeleteSession(sessionId).then((res) => {
    // 从历史记录列表中移除会话
    sessions.value = sessions.value.filter(
      (session) => session.id !== sessionId
    )
    // 如果删除的是当前选中的会话，清空消息列表
    if (activeSessionId.value === sessionId) {
      messages.value = []
      activeSessionId.value = null
      // 如果还存在对话历史就选中第一条
      if (sessions.value.length > 0) {
        loadDialogue(sessions.value[0])
      }
    }
  })
}

// 获取会话列表
const loadSessions = (page) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  ChatSessionList({ page: page, limit: sessionLimit.value })
    .then((res) => {
      sessions.value = res.data
      sessionListCount.value = res.count
      // 默认选中第一个会话
      if (sessions.value.length > 0) {
        loadDialogue(sessions.value[0])
      }
    })
    .finally(() => {
      loadingInstance.close()
    })
}
// 往下滚动加载会话列表
const handleScroll = () => {
  if (
    messagesContainer.value.scrollTop + messagesContainer.value.clientHeight >=
    messagesContainer.value.scrollHeight
  ) {
    // 滚动到底部，加载下一页
    if (sessionPage.value * sessionLimit.value < sessionListCount.value) {
      const loadingInstance = ElLoading.service({ fullscreen: true })
      sessionPage.value++
      ChatSessionList({ page: sessionPage.value, limit: 11 })
        .then((res) => {
          sessionListCount.value = res.count
          sessions.value = sessions.value.concat(res.data)
        })
        .finally(() => {
          loadingInstance.close()
        })
    }
  }
}

// 获取指定会话列表中的消息列表
const loadDialogue = (session) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  const sessionId = session.id
  selectedModel.value = session.model_id
  activeSessionId.value = sessionId
  ChatDialogueList({ session_id: sessionId, page: dialoguePage.value })
    .then((res) => {
      dialogueListCount.value = ref.count
      // 提取对话数据
      const dialogues = res.data
      messages.value = dialogues
        .map((dialogue) => [
          { sender: 'user', content: dialogue.query },
          { sender: 'bot', content: dialogue.answer }
        ])
        .flat() // 将嵌套数组展平
      scrollToBottom()
    })
    .finally(() => {
      loadingInstance.close()
    })
}

// 发送问题
const sendQuery = () => {
  if (query.value.trim() === '') return
  messages.value.push({ sender: 'user', content: query.value })
  const user_query = query.value
  query.value = ''
  selectIsLoading.value = true
  inputDisabled.value = true
  isLoading.value = true
  scrollToBottom()
  ChatAnswer({ query: user_query, session_id: activeSessionId.value })
    .then((res) => {
      messages.value.push({ sender: 'bot', content: res.data.answer })
      if (res.data.session_id !== activeSessionId.value) {
        // 如果会话id不一致，则更新会话列表
        loadSessions(1)
      }
      if (res.data.model_id !== selectedModel.value) {
        console.log('model_id', res.data.model_id)
        selectedModel.value = res.data.model_id
      }
      activeSessionId.value = res.data.session_id

      scrollToBottom()
    })
    .finally(() => {
      selectIsLoading.value = false
      isLoading.value = false
      inputDisabled.value = false
    })
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

onMounted(() => {
  loadSessions(sessionPage.value)
  scrollToBottom()
  fetchModels()
  userAllKnowledge()
})
</script>

<style scoped>
.transparent-button {
  background-color: transparent !important;
  border-color: transparent !important;
}

/* 如果需要，可以添加鼠标悬停时的效果 */
.transparent-button:hover {
  background-color: transparent !important;
  border-color: transparent !important;
}

/* 如果需要，可以添加点击时的效果 */
.transparent-button:active {
  background-color: transparent !important;
  border-color: transparent !important;
}
/* 确保 html 和 body 占满整个屏幕高度，并禁止全局滚动 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden; /* 禁止全局滚动 */
}

.chat-container {
  display: flex;
  /* height: calc(100vh - 20px); */
  height: 780px;
  background-color: #f5f5f5;
  overflow: hidden; /* 禁止容器滚动 */
}

.history-sidebar {
  height: 100%;
  width: 240px;
  background-color: #ffffff; /* 白色背景 */
  border: 1px solid #dbd9d9; /* 黑色边框，宽度为1px，样式为实线 */
  border-radius: 8px; /* 圆角边框，半径可以根据需要调整 */
  padding: 20px;
  overflow-y: auto; /* 允许侧边栏内部滚动 */
}

.history-sidebar h2 {
  margin-bottom: 20px;
}

.history-sidebar ul {
  list-style: none;
  padding: 0;
}

.history-sidebar li {
  padding: 10px;
  cursor: pointer;
  border-radius: 5px; /* 灰色圆角边框 */
  border: 1px solid #e7e2e2; /* 灰色边框 */
  border-radius: 5px;
  margin-bottom: 5px;
  color: black; /* 确保字体颜色为白色 */
}

.history-sidebar li:hover {
  background-color: #75afe9;
}

.history-sidebar li.active {
  background-color: #c4ecec;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow: hidden; /* 禁止聊天窗口滚动 */
}

.messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto; /* 允许消息区域内部滚动 */
  overflow-x: hidden; /* 禁止水平滚动 */
}

.message {
  margin-bottom: 15px;
  display: flex;
}
.sidebar-header {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 标题和按钮分开 */
  margin-bottom: 20px;
}

.add-session-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0 10px;
}

.add-session-btn:hover {
  color: #1abc9c; /* 鼠标悬停时改变颜色 */
}
.message.user {
  justify-content: flex-end;
}

.message.bot {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
}

.md-editor-preview {
  border: none !important; /* 移除边框 */
  background-color: transparent !important; /* 移除背景色 */
}
.message.user .message-content {
  background-color: #1abc9c;
  color: white;
}

.loading {
  color: #666;
  font-style: italic;
}

.input-area {
  display: flex;
  padding: 13px;
  background-color: #f5f5f5;
  border-top: 1px solid #ddd;
}

.input-area .el-input-group {
  flex: 1;
  padding: 10px;
  /* border: 1px solid #ddd; */
  /* border-radius: 5px;
  margin-right: 10px; */
}
.input-area .dropdown {
  /* flex: 1px; */
  padding: 10px;
  /* border: 1px solid #ddd; */
  border-radius: 5px;
  margin-right: 1px;
  width: 200px; /* 设置固定宽度 */
}

.input-area button {
  /* padding: 10px 20px; */
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 9px;
  cursor: pointer;
}

.input-area button:hover {
  background-color: #16a085;
}
.session-item {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 名称和按钮分开 */
  width: 100%; /* 占满父容器宽度 */
}
.session-actions {
  display: flex;
  gap: 5px; /* 按钮之间的间距 */
  justify-content: flex-end;
  align-items: center;
}
.session-actions .el-button {
  margin-left: 5px; /* 调整按钮之间的间距 */
}

.edit-btn,
.delete-btn {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  padding: 0;
}

.edit-btn:hover {
  color: #1abc9c; /* 鼠标悬停时改变颜色 */
}

.delete-btn:hover {
  color: #e74c3c; /* 鼠标悬停时改变颜色 */
}

li input {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 5px;
  width: 60%; /* 输入框宽度 */
}
/* 自定义滚动条样式 */
.custom-scrollbar::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent; /* 轨道背景，默认透明 */
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: transparent; /* 滚动条滑块，默认透明 */
  border-radius: 4px; /* 滑块圆角 */
}

.custom-scrollbar:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1); /* 滚动时滑块颜色 */
}

.el-button--plain.red-icon {
  background-color: transparent;
  border: none;
}
.truncated-input {
  width: 80px; /* 根据需要调整宽度 */
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}
</style>
